package com.amir.common.mvp.presenter;


import com.amir.common.mvp.IModel;
import com.amir.common.mvp.view.IView;
import com.amir.common.utils.LogUtils;

import java.lang.ref.WeakReference;

import androidx.annotation.Nullable;

public class BasePresenter<V extends IView> implements IPresenter<V> {
    private WeakReference<V> referenceView;
    private WeakReference<IModel> referenceModel;

    public BasePresenter(V view) {
        attachView(view);
        LogUtils.Companion.E(getClass().getSimpleName(), "detachView");
    }

    @Override
    public void attachView(V view) {
        if (view == null)
            throw new NullPointerException("view can not be null when in attachview() in BasePresenter");
        else {
            if (referenceView == null)
                referenceView = new WeakReference<>(view);//将View置为弱引用，当view被销毁回收时，依赖于view的对象（即Presenter）也会被回收，而不会造成内存泄漏 }

        }

    }

    @Override
    public void attachModel(IModel model) {
        if (model == null)
            throw new NullPointerException("view can not be null when in attachview() in BasePresenter");
        else {
            if (referenceView == null)
                referenceModel = new WeakReference<>(model);
            //将View置为弱引用，当view被销毁回收时，依赖于view的对象（即Presenter）也会被回收，而不会造成内存泄漏 }

        }

    }


    @Override
    public void detachView() {
        LogUtils.Companion.E(getClass().getSimpleName(), "detachView");
        if (referenceView != null) {
            referenceView.clear();
            referenceView = null;
        }


    }

    @Nullable
    public V getMvpView() {
        if (isAttachView()) return referenceView.get();
        else return null;
    }


    public boolean isAttachView() {
        return referenceView != null && referenceView.get() != null;
    }


}
